<template>
  <div ref="echartContainer" class="echart-container"></div>
</template>

<script>
import * as echarts from 'echarts' // 引入 echarts

// import echarts from 'echarts'

export default {
  name: 'CommonEcharts',
  props: {
    // 接收一个 options 对象，用于配置 ECharts 图表
    options: {
      type: Object,
      required: true,
      default: () => ({}) // 默认一个空对象
    }
  },
  data() {
    return {
      chartInstance: null, // 用于存储 ECharts 实例
      resizeObserver: null // 用于存储 ResizeObserver 实例
    }
  },
  watch: {
    // 监听 options 的变化，当 options 改变时，重新渲染图表
    options: {
      handler(newOptions) {
        if (this.chartInstance) {
          this.chartInstance.setOption(newOptions)
        }
      },
      deep: true // 深度监听，确保子属性的变化也能触发更新
    }
  },
  mounted() {
    this.initChart() // 组件挂载完成后初始化图表
    // 添加窗口大小改变事件监听
    if (window.ResizeObserver) {
      this.initResizeObserver()
    } else {
      window.addEventListener('resize', this.resizeChart)
    }
  },
  beforeDestroy() {
    // 组件销毁前，取消 ResizeObserver 监听或移除事件监听器，并销毁 ECharts 实例
    if (window.ResizeObserver) {
      this.disconnectResizeObserver()
    } else {
      window.removeEventListener('resize', this.resizeChart)
    }
    if (this.chartInstance) {
      this.chartInstance.dispose()
      this.chartInstance = null
    }
  },
  methods: {
    initChart() {
      const chartDom = this.$refs.echartContainer
      if (chartDom) {
        this.chartInstance = echarts.init(chartDom)
        this.chartInstance.setOption(this.options)
      }
    },
    /**
     * 响应容器大小变化，重新渲染图表
     */
    resizeChart() {
      if (this.chartInstance) {
        this.chartInstance.resize()
      }
    },

    /**
     * 初始化 ResizeObserver 实例
     */
    initResizeObserver() {
      const chartDom = this.$refs.echartContainer
      if (chartDom && window.ResizeObserver) {
        this.resizeObserver = new ResizeObserver(() => {
          this.resizeChart()
        })
        this.resizeObserver.observe(chartDom)
      }
    },

    disconnectResizeObserver() {
      if (this.resizeObserver) {
        this.resizeObserver.disconnect()
        this.resizeObserver = null
      }
    }
  }
}
</script>

<style scoped>
.echart-container {
  width: 100%;
  height: 100%;
}
</style>
